xquery version "1.0";

declare variable $menuXMLDocPath external;
declare variable $planXMLDocPath external;
declare variable $menuId external;

declare function local:getMenuDayNumber() as xs:integer? {
	let $menuDoc := doc($menuXMLDocPath)//Menu
	for $menu in $menuDoc
	where $menu/@id = $menuId
	return $menu/numberday
};

declare function local:getMenuMealNumber() as xs:integer? {
	let $menuDoc := doc($menuXMLDocPath)//Menu
	for $menu in $menuDoc
	where $menu/@id = $menuId
	return $menu/numbermeal
};

let $numberDay := local:getMenuDayNumber() 
let $numberMeal := local:getMenuMealNumber() 

let $planList := doc($planXMLDocPath)//PlanInMeal
for $i in 0 to ($numberDay * $numberMeal)-1, $plan in $planList
where $plan/menuId = $menuId and $plan/mealOrder - 1 = $i
return <dish day='{floor($i div $numberMeal) + 1}' meal='{$i mod $numberMeal + 1}'>{$plan//Dish/name}</dish>